package com.eshore.norm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.eshore.norm.pojo.constant.Const;
import com.eshore.norm.pojo.dto.NormSubnet;
import com.eshore.norm.mapper.NormSubnetMapper;
import com.eshore.norm.pojo.po.NormSubnetPO;
import com.eshore.norm.service.INormSubnetService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eshore.norm.util.DateUtils;
import com.eshore.norm.util.ListStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 子网列表 服务实现类
 * </p>
 *
 * @author chenjl
 * @since 2024-01-05
 */
@Service
public class NormSubnetServiceImpl extends ServiceImpl<NormSubnetMapper, NormSubnet> implements INormSubnetService {

    @Override
    public void dataImport(NormSubnetPO po) {
        Optional<NormSubnetPO> po_optional = Optional.ofNullable(po);
        po_optional.ifPresent(s -> {
            Optional<List<NormSubnetPO.SubnetsDTO>> dto_optional = Optional.ofNullable(s.getSubnets());
            dto_optional.ifPresent(item -> {
                List<String> newSubnetIds = item.stream().map(NormSubnetPO.SubnetsDTO::getId).collect(Collectors.toList());
                cleanOldData(Const.CONFIG_ID, newSubnetIds);
                //将po转化成实体对象入库
                List<NormSubnet> entityList = toSubnet(Const.CONFIG_ID, dto_optional);
                if (!CollectionUtils.isEmpty(entityList)) {
                    getBaseMapper().insertOrUpdateBatch(entityList);
                }
            });
        });
    }

    /**
     * 删除现已不存在的数据，保持同步一致
     *
     * @param configId
     * @param newSubnetIds 需要同步的索引Id集合
     * @author v-chenjl62
     * @date 2024/1/10
     */
    private void cleanOldData(Long configId, List<String> newSubnetIds) {
        List<String> oldSubnetIds = lambdaQuery().eq(NormSubnet::getConfigId, configId).list().stream().map(NormSubnet::getSubnetId).collect(Collectors.toList());
        //筛选出差异的xxxId即为多余的需要删除
        oldSubnetIds.removeAll(newSubnetIds);
        if (!CollectionUtils.isEmpty(oldSubnetIds)) {
            getBaseMapper().delete(new QueryWrapper<NormSubnet>().in("subnet_id", oldSubnetIds));
        }
    }

    private List<NormSubnet> toSubnet(Long configId, Optional<List<NormSubnetPO.SubnetsDTO>> list_optional) {
        return list_optional.get().stream().map(item -> {
            NormSubnet entity = new NormSubnet();
            BeanUtils.copyProperties(item, entity, "id", "allocationPools", "dnsNameservers", "hostRoutes", "serviceTypes", "tags");
            entity.setSubnetId(item.getId());//xxxId 是唯一索引
            entity.setAllocationPools(JSON.toJSONString(item.getAllocationPools(), SerializerFeature.WriteMapNullValue));
            entity.setDnsNameservers(JSON.toJSONString(item.getDnsNameservers(), SerializerFeature.WriteMapNullValue));
            entity.setHostRoutes(JSON.toJSONString(item.getHostRoutes(), SerializerFeature.WriteMapNullValue));
            entity.setServiceTypes(JSON.toJSONString(item.getServiceTypes(), SerializerFeature.WriteMapNullValue));
            entity.setTags(ListStringUtils.listToString(item.getTags()));

            entity.setId(IdWorker.getId());
            entity.setConfigId(configId);
//            entity.setCreateDate(LocalDateTime.now());
//            entity.setUpdateDate(LocalDateTime.now());
            entity.setCreateDate(DateUtils.parse(item.getCreatedAt(),DateUtils.DATE_TIME_T_PATTERN));
            entity.setUpdateDate(DateUtils.parse(item.getUpdatedAt(),DateUtils.DATE_TIME_T_PATTERN));
            return entity;
        }).collect(Collectors.toList());

    }
}
